﻿namespace SanalMagaza.Model
{
    using System.Collections.Generic;
    using System.Linq;
    using SanalMagaza.Model.ViewModel;

    public class Repository
    {
        private readonly SanalMagazaDataContext _context;
        public Repository()
        {
            _context = new SanalMagazaDataContext();
        }

        public IList<Category> GetAllCategory()
        {
            return _context.Categories.ToList();
        }

        public List<Product> GetAllProductByShowCase()
        {
            return _context.Products.Where(d => d.ShowCase).ToList();
        }

        public List<Product> GetAllProduct(ProductFilter filter)
        {
            var list = _context.Products.AsQueryable();
            if (!string.IsNullOrEmpty(filter.Category))
            {
                list = list.Where(d => d.Category.Seo == filter.Category);
            }
            if (!string.IsNullOrEmpty(filter.SearchString))
                list = list.Where(d => d.Title.Contains(filter.SearchString));

            if (filter.ProductOrder != null)
            {
                switch (filter.ProductOrder.Value)
                {
                    case ProductOrder.Title:
                        list = filter.OrderDir.GetValueOrDefault() == OrderDir.Asc ? list.OrderBy(d => d.Title) : list.OrderByDescending(d => d.Title);
                        break;
                    case ProductOrder.Price:
                        list = filter.OrderDir.GetValueOrDefault() == OrderDir.Asc ? list.OrderBy(d => d.Price) : list.OrderByDescending(d => d.Price);
                        break;
                    case ProductOrder.Category:
                        list = filter.OrderDir.GetValueOrDefault() == OrderDir.Asc ? list.OrderBy(d => d.CategoryId) : list.OrderByDescending(d => d.CategoryId);
                        break;
                }
            }
            //Paging PageSize , sayfa değiştirme
            return list.ToList();
        }

        public Product GetProduct(string seo)
        {
            if (string.IsNullOrEmpty(seo))
                return null;
            var product = _context.Products.SingleOrDefault(d => d.Seo.ToLower() == seo.ToLower());
            return product;
        }
    }
}
